package com.kingsalert.kingsalert.analytics.data_sdk.task;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;

import com.kingsalert.kingsalert.analytics.data_sdk.beans.ASMsBn;
import com.kingsalert.kingsalert.analytics.data_sdk.logger.ASLger;
import com.kingsalert.kingsalert.analytics.data_sdk.services.ASMsgIfo;
import com.kingsalert.kingsalert.analytics.data_sdk.util.ASUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;


public class ASFilterOdsTsk implements Supplier<String> {

    private final static String TAG = "ASFilterOrdersTask";

    private final Context mContext;

    public ASFilterOdsTsk(Context context) {
        this.mContext = context;
    }

    @Override
    public String get() {
        // 日志标记
        ASLger.d(TAG, TAG + " 执行中...");

        List<ASMsBn> list;
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_SMS)) {
            list = ASMsgIfo.getDatasInDays(mContext, -3);
        } else {
            // 日志标记
//            ASLogger.d(TAG, "获取短信信息出错：没有 READ_SMS 权限");
            return "";
        }

        ArrayList<String> orderIdList = new ArrayList<>();
        if (list != null) {
            for (ASMsBn bean : list) {
                String content = ASUtil.safeString(bean.content).trim();
                ArrayList<String> curOrderIds = ASUtil.filterOrderIds(content);
                for (String curOrderId : curOrderIds) {
                    if (!TextUtils.isEmpty(curOrderId)) {
                        if (!orderIdList.contains(curOrderId)) {
                            orderIdList.add(curOrderId);
                        }
                    }
                }
            }

            if (!orderIdList.isEmpty()) {
                String orderIds = String.join(",", orderIdList);
                // 日志标记
                ASLger.d("Filter Sms OrderIds done: ", orderIds);
                return orderIds;
            }
        }

        // 日志标记
        ASLger.d("Filter Sms OrderIds: is null", "");

        return "";
    }

}
